package com.hanxiaozhang.threadbase1ndedition.producerandconsumer;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用synchronized实现生产者与消费者〉
 *
 * @author hanxinghua
 * @create 2021/11/12
 * @since 1.0.0
 */
public class No1UseSynchronized {

    public static void main(String[] args) throws InterruptedException {

        No1Platform platform = new No1Platform();

        // 生产者每10ms生成一个汉堡
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.increment();
            }
        }, "Producer");
        // 消费者每5ms消耗一个汉堡
        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.decrement();
            }
        }, "Consumer");

        producer.start();
        TimeUnit.MILLISECONDS.sleep(80);
        consumer.start();

    }

}


class No1Platform {

    private int hamburger = 0;

    private static final int MAX_THRESHOLD = 5;


    /**
     * 自增
     */
    public synchronized void increment() {

        while (hamburger == MAX_THRESHOLD) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        hamburger++;
        System.out.println("increment hamburger,current is " + hamburger);
        notify();
    }


    /**
     * 自减
     */
    public synchronized void decrement() {

        while (hamburger == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        hamburger--;
        System.out.println("decrement hamburger,current is " + hamburger);
        notify();
    }


}



